package org.example.controller;

import org.example.dto.ApiResponse;
import org.example.dto.CreateShortUrlRequest;
import org.example.dto.CreateShortUrlResponse;
import org.example.entity.ShortUrl;
import org.example.service.ShortUrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 短链接控制器
 * 
 * @author Your Name
 * @since 2024-07-01
 */
@RestController
@RequestMapping("/api/short-url")
public class ShortUrlController {
    
    @Autowired
    private ShortUrlService shortUrlService;
    
    /**
     * 创建短链接
     */
    @PostMapping("/create")
    public ApiResponse<CreateShortUrlResponse> createShortUrl(@Valid @RequestBody CreateShortUrlRequest request) {
        CreateShortUrlResponse response = shortUrlService.createShortUrl(request);
        if (response.getSuccess()) {
            return ApiResponse.success("短链接创建成功", response);
        } else {
            return ApiResponse.error(400, response.getMessage());
        }
    }
    
    /**
     * 获取短链接信息
     */
    @GetMapping("/{shortCode}")
    public ApiResponse<ShortUrl> getShortUrlInfo(@PathVariable String shortCode) {
        ShortUrl shortUrl = shortUrlService.getShortUrlInfo(shortCode);
        if (shortUrl != null) {
            return ApiResponse.success(shortUrl);
        } else {
            return ApiResponse.error(404, "短链接不存在");
        }
    }
    
    /**
     * 获取所有短链接
     */
    @GetMapping("/list")
    public ApiResponse<List<ShortUrl>> getAllShortUrls() {
        List<ShortUrl> shortUrls = shortUrlService.getAllShortUrls();
        return ApiResponse.success(shortUrls);
    }
    
    /**
     * 分页获取短链接
     */
    @GetMapping("/page")
    public ApiResponse<List<ShortUrl>> getShortUrlsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        List<ShortUrl> shortUrls = shortUrlService.getShortUrlsByPage(page, size);
        return ApiResponse.success(shortUrls);
    }
    
    /**
     * 更新短链接状态
     */
    @PutMapping("/{shortCode}/status")
    public ApiResponse<String> updateShortUrlStatus(
            @PathVariable String shortCode,
            @RequestParam Integer status) {
        boolean success = shortUrlService.updateShortUrlStatus(shortCode, status);
        if (success) {
            return ApiResponse.success("状态更新成功");
        } else {
            return ApiResponse.error("状态更新失败");
        }
    }
    
    /**
     * 删除短链接
     */
    @DeleteMapping("/{shortCode}")
    public ApiResponse<String> deleteShortUrl(@PathVariable String shortCode) {
        boolean success = shortUrlService.deleteShortUrl(shortCode);
        if (success) {
            return ApiResponse.success("删除成功");
        } else {
            return ApiResponse.error("删除失败");
        }
    }
    
    /**
     * 获取访问统计
     */
    @GetMapping("/{shortCode}/statistics")
    public ApiResponse<Long> getAccessCount(@PathVariable String shortCode) {
        Long accessCount = shortUrlService.getAccessCount(shortCode);
        return ApiResponse.success(accessCount);
    }
    
    /**
     * 短链接重定向（用于访问短链接）
     */
    @GetMapping("/{shortCode}/redirect")
    public void redirectToOriginalUrl(
            @PathVariable String shortCode,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        
        String ipAddress = getClientIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        String referer = request.getHeader("Referer");
        
        String originalUrl = shortUrlService.redirectToOriginalUrl(shortCode, ipAddress, userAgent, referer);
        
        if (originalUrl != null) {
            response.sendRedirect(originalUrl);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("短链接不存在或已过期");
        }
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
